package com.community.zhihuishequ.view.monitor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.community.zhihuishequ.R;
import com.community.zhihuishequ.third.HikInterface;
import com.community.zhihuishequ.third.hik.widget.CustomSurfaceView;
import com.community.zhihuishequ.view.base.BaseActivity;
import com.community.zhihuishequ.widget.GamePad;
import com.hikvision.sdk.VMSNetSDK;
import com.hikvision.sdk.consts.SDKConstant;
import com.hikvision.sdk.net.bean.CustomRect;
import com.hikvision.sdk.net.bean.SubResourceNodeBean;
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 营区监控
 */
public class MonitorVideoActivity extends BaseActivity implements SurfaceHolder.Callback {
    public static final String EXTRA_NODE = "node";
    public static final String EXTRA_VIDEO_QUALITY = "video_quality";
    public static final String EXTRA_PID = "pid";

    private CustomSurfaceView svPreview;
    private GamePad gamePad;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//
        setContentView(R.layout.activity_monitor_video);

        Toolbar topToolBar = findViewById(R.id.toolBar);
        setSupportActionBar(topToolBar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        svPreview = findViewById(R.id.surfaceView);
        svPreview.setOnZoomListener(new CustomSurfaceView.OnZoomListener() {
            @Override
            public void onZoomChange(CustomRect original, CustomRect current) {
                VMSNetSDK.getInstance().zoomLiveOpt(1, true, original, current);
            }
        });
        svPreview.getHolder().addCallback(this);
        gamePad = findViewById(R.id.gamepad);
        if (getPid()) {
            gamePad.setVisibility(View.VISIBLE);
            adjustmentDirection();
        } else {
            gamePad.setVisibility(View.GONE);
        }
    }

    private boolean getPid() {
        Intent intent = getIntent();
        String pid = "";
        if (intent != null) {
            pid = intent.getStringExtra(EXTRA_PID);
        }
        if (!StringUtils.isEmpty(pid) && pid.equals("3")) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MonitorController.getInstance().doStopLive(1);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onToastEvent(MonitorToastEvent event) {
        showToast(event.getMsg());
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        Intent intent = getIntent();
        SubResourceNodeBean node = (SubResourceNodeBean) intent.getSerializableExtra(EXTRA_NODE);
        int videoQuality = intent.getIntExtra(EXTRA_VIDEO_QUALITY, HikInterface.HD);

        MonitorController.getInstance().doStartLive(1, node, svPreview, videoQuality, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
            }
        });
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    /**
     * 调整球机方向
     */
    private void adjustmentDirection() {
        gamePad.setOnDirectionListener(new GamePad.OnDirectionListener() {
            @Override
            public void onUp() {
                hikYunStart(MonitorConfig.HIKYUNCONTROLLERUP);
            }

            @Override
            public void onDown() {
                hikYunStart(MonitorConfig.HIKYUNCONTROLLERDOWN);
            }

            @Override
            public void onLeft() {
                hikYunStart(MonitorConfig.HIKYUNCONTROLLERLEFT);
            }

            @Override
            public void onRight() {
                hikYunStart(MonitorConfig.HIKYUNCONTROLLERRIGHT);
            }
        });
    }

    /**
     * status = 21   云台转上（使摄像头向上转动）
     * status = 22   云台转下（使摄像头向下转动）
     * status = 23   云台转左（使摄像头向左转动）
     * status = 24   云台转右（使摄像头向右转动）
     *
     * @param status
     */
    private void hikYunStart(final int status) {
        VMSNetSDK.getInstance().sendPTZCtrlCommand(1, true, SDKConstant.PTZCommandConstant.ACTION_START, status, 256, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                hikYunStop(status);
                ToastUtils.showShort(R.string.error_network);
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                hikYunStop(status);
            }
        });
    }

    private void hikYunStop(int status) {
        VMSNetSDK.getInstance().sendPTZCtrlCommand(1, true, SDKConstant.PTZCommandConstant.ACTION_STOP, status, 256, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
            }
        });
    }

}
